// 实现这个项目的构建任务
const {src, dest, parallel, series, watch} = require('gulp')
const del = require('del')

const browserSync = require('browser-sync')
const bs = browserSync.create()

const loadPlugins = require('gulp-load-plugins')  // 自动加载所有的 gulp 插件
const plugins = loadPlugins() 

// const sass = require('gulp-sass')
// const babel = require('gulp-babel')
// const swig = require('gulp-swig')
// const imagemin = require('gulp-imagemin')

const data = require("./package.json")

// 处理 css
const style = () => {
    return src('src/assets/styles/*.scss' ,{ base: 'src'})  //第二个参数 输出基准目标
            .pipe(plugins.sass({outputStyle:'expanded'}))
            .pipe(dest('temp'))
            .pipe(bs.reload({stream:true}))
}
// 处理 js
const script = () => {
    return src('src/assets/scripts/*.js', {base: 'src'})
            .pipe(plugins.babel({presets:['@babel/preset-env']}))
            .pipe(dest('temp'))
            .pipe(bs.reload({stream:true}))

}
// 处理 html
const page = () => {
    return src('src/*.html',{base:'src'})
            .pipe(plugins.swig({data,defaults:{cache:false}})) //防止模板缓存导致页面不刷新
            .pipe(dest('temp'))
            .pipe(bs.reload({stream:true}))

}
// 处理 图片
const image = () => {
  return src('src/assets/images/**',{base:'src'})
        .pipe(plugins.imagemin())
        .pipe(dest('dist'))
}
// 处理 字体
const font = () => {
  return src('src/assets/fonts/**', { base:'src' })
        .pipe(plugins.imagemin())
        .pipe(dest('dist'))
}
// 复制静态资源
const extra = () => {
  return src('public/**', { base:'src' })
        .pipe(dest('dist'))
}

// 清除构建后的目录
const clean = () => {
  return del(['dist','temp'])
}
// 开启服务
const serve = () => {
  watch('src/assets/styles/*.scss',style)
  watch('src/assets/scripts/*.js',script)
  watch('src/*.html',page)
  watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**'
  ],bs.reload)

  bs.init({
    notify:false,
    port:2020,
    // open:false,  //是否默认打开浏览器
    // files:'dist/**',  //指定哪些文件发生改变会 浏览器自动刷新
    server:{
      baseDir:['temp','src','public'],
      routes:{
        '/node_modules':'node_modules'
      }
    }
  })
}
// 文件压缩处理
const useref = () => {
  return src('temp/*.html',{base:'temp'})
        .pipe(plugins.useref({searchPath:['temp','.']}))
        .pipe(plugins.if(/\.js$/,plugins.uglify()))
        .pipe(plugins.if(/\.css$/,plugins.cleanCss()))
        .pipe(plugins.if(/\.html$/,plugins.htmlmin({
          collapseWhitespace:true,
          minifyCSS:true,
          minifyJS:true
        })))
        .pipe(dest('dist'))
}

const compile = parallel(style,script,page)

const build = series(clean,
  parallel(series(compile,useref),
  extra,
  image,
  font
  ))

const develop = series(compile,serve)

module.exports = {
    clean,
    build,
    develop,
    serve
}